package com.advert.service.mail;

import com.advert.config.Config;
import com.advert.dto.mail.Mail;
import com.advert.exception.ApplicationRuntimeException;
import com.advert.config.MailConfig;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.*;
import org.jboss.seam.log.Log;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@Name("MailService")
@Scope(ScopeType.APPLICATION)
@AutoCreate
public class MailService {
    @Logger
    private Log logger;

    @In("config")
    private Config config;
    private Session session;


    public void sendMail(Mail mail) {
        try {
            Transport transport = session.getTransport(mailConfig().getProtocol());
            transport.connect(mailConfig().getHost(), mailConfig().getPort(), mailConfig().getUser(), mailConfig().getPassword());
            Message message = buildMessage(mail);
            if (message != null) {
                transport.sendMessage(message, new Address[] {new InternetAddress(mail.getAddress())});
            }
            transport.close();
        } catch (MessagingException e) {
            logger.error("Message sending failed to {0}.", e, mail.getAddress());
            throw new ApplicationRuntimeException("Message sending failed.", e);
        }
    }

    private Message buildMessage(Mail mail) {
        MimeMessage message = null;

        if (mail.getAddress() != null && mail.getAddress().length() > 0 && mail.getSubject() != null && mail.getMessage() != null) {
            try {
                message = new MimeMessage(session);
                message.setSubject(mail.getSubject(), "UTF-8");
                message.setText(mail.getMessage(), "UTF-8");
                Address addressTo = new InternetAddress(mail.getAddress());
                Address addressFrom = new InternetAddress(mailConfig().getFromAddress());
                try {
                    addressFrom = new InternetAddress(mailConfig().getFromAddress(), mailConfig().getFromName());
                } catch (UnsupportedEncodingException e) {}
                message.setFrom(addressFrom);
                message.addRecipient(Message.RecipientType.TO, addressTo);
                message.saveChanges();

            } catch (MessagingException e) {
                logger.error("Message for {0} build failed.", e, mail.getAddress());
                throw new ApplicationRuntimeException("Message build failed.", e);
            }
        }

        return message;
    }


    @Create
    public void init() {
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.auth", String.valueOf(mailConfig().getSmtpAuth()));
        session = Session.getInstance(props, null);
    }

    private MailConfig mailConfig() {
        return config.getMailConfig();
    }
}
